// 因为这个国家地区列表选项在登录，注册等多个页面都需要使用，所以我们把它设置在公共组件中
import {useEffect,useState, TouchEvent} from 'react'
import {NavBar,Icon,List} from "antd-mobile"
import {RouteComponentProps}  from "react-router-dom"

// 引用api接口文件
import {reqGetCountryData} from "../../api/common"
import {AxiosResponse} from "axios"

import "./index.less"
// 提取解构item
const { Item }= List;
interface CountryData {
    [propName: string]: Country[];
  }
  
  interface Country {
    [propName: string]: string;
  }
export default function CountryPicker(props: RouteComponentProps) {
    const [countryData, setCountryData] = useState<CountryData>({});
    useEffect(()=>{
        reqGetCountryData()
        // 成功
        // response还要做类型定义
        .then((response:AxiosResponse)=>{
            setCountryData( response.data.data);
        })
        // 失败
        .catch((err)=>{
            console.log(err);
        })
    },[])
    // 1. 提取countryData所有key属性
    const countryKeys: string[] = Object.keys(countryData);

    //事件委托
    // 点击跳转国家
    const goCountry = (e: TouchEvent) => {
        const key: string = (e.target as HTMLLIElement).innerText;
        //  window.scrollTo(x, y) 让滚动条滚动到指定位置
        window.scrollTo(
          0,
          (document.getElementById(key) as HTMLElement).offsetTop - 45
        );
      };
    // 点击返回注册页面
    const goRegister = (code: string) => {
        return () => {
      // 路由组件传参：state
      props.history.push("/phoneRegister", code);
    };
  };


    return (
        <div className="Country-Picker">
           <NavBar 
                className="Country-Pick-top"
                mode="light"
                icon={<Icon className="left-icon" type="left" />}
                onLeftClick={() => props.history.goBack()}>
                选择国家或地区
            </NavBar>
            {/* 使用ant-d的列表组件 */}
        <div className="Country-Pick-container">
            {/* 2. 遍历countryKeys */}
            {countryKeys.map((key: string) => {
                return (
                    // List组件不能指定id属性，所以给外层包裹一个div
                    <div id={key} key={key}>
                        <List renderHeader={() => key}>
                            {countryData[key].map((item: Country, index: number) => {
                            // item { '中国': '86' }
                            const key: string = Object.keys(item)[0];
                                const value: string = "+" + item[key];
                                return (
                                <Item extra={value} key={index} onClick={goRegister(value)}>
                                {key}
                                </Item>
                             );
                            })}
                        </List>
                    </div>
                     );
        })}
        </div>
        <ul className="country-picker-sidebar" onTouchEnd={goCountry}>
        {countryKeys.map((key: string) => {
          return <li key={key}>{key}</li>;
        })}
      </ul>
    </div>
    )
}
